package com.artisan.pf4j.controller;

import com.artisan.pf4j.api.Greeting;
import org.pf4j.PluginManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 问候控制器
 * 演示如何在宿主应用中调用插件扩展
 */
@RestController
public class GreetingController {

    private final PluginManager pluginManager;

    public GreetingController(PluginManager pluginManager) {
        this.pluginManager = pluginManager;
    }

    /**
     * 问候接口
     * @param name 姓名参数
     * @return 问候语
     */
    @GetMapping("/greet")
    public String greet(@RequestParam(defaultValue = "World") String name) {
        // 获取所有 Greeting 扩展实现
        List<Greeting> greetings = pluginManager.getExtensions(Greeting.class);
        
        if (greetings.isEmpty()) {
            return "No Greeting plugin found! Please check if plugins are loaded correctly.";
        }
        
        // 使用第一个找到的插件实现
        return greetings.get(0).sayHello(name);
    }

    /**
     * 获取所有插件信息
     * @return 插件信息列表
     */
    @GetMapping("/plugins")
    public String getPlugins() {
        StringBuilder sb = new StringBuilder();
        sb.append("Loaded plugins:\n");
        
        pluginManager.getPlugins().forEach(plugin -> {
            sb.append("- Plugin ID: ").append(plugin.getPluginId())
              .append(", Version: ").append(plugin.getDescriptor().getVersion())
              .append(", State: ").append(plugin.getPluginState())
              .append("\n");
        });
        
        List<Greeting> greetings = pluginManager.getExtensions(Greeting.class);
        sb.append("\nGreeting extensions found: ").append(greetings.size());
        
        return sb.toString();
    }
}
